package com.itheima.Servlet;

import com.itheima.domain.Student;
import com.sun.org.apache.bcel.internal.generic.NEW;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;

@WebServlet("/stu/deleteStudent")
public class deleteStudent extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {




        String sid = req.getParameter("sid");

        // 读取/stu.txt中的数据
        //.创建字符输入流对象，关联读取的文件
        String realPath = getServletContext().getRealPath("stu.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(realPath),"UTF-8"));
            //创建集合 把学生信息赛到集合中
        ArrayList<Student> list = new ArrayList<>();
        //循环读取
        String line;
        while ((line=br.readLine())!=null){
            Student stu = new Student();
            String[] split = line.split(",");
            stu.setSid(split[0]);
            stu.setUsername(split[1]);
            stu.setAge(Integer.parseInt(split[2]));
            stu.setScore(Integer.parseInt(split[3]));
            list.add(stu);
        }
        //遍历集合 得到学生id 进行校验
        for (int i = 0; i < list.size(); i++) {
            Student stu = list.get(i);
            if(stu.getSid().equals(sid)){
                list.remove(i);
            }
        }
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(realPath),"utf-8"));
        for (Student student : list) {
            bw.write(student.toString());
            bw.newLine();
            bw.flush();
        }
        bw.close();
        //请求转发到查看页面
        req.getRequestDispatcher("/stu/findAllStudent").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
